import Cache from '@/plugins/cache'
import {getInitApi} from '@/api/login'

const cacheKey = 'vv__sidebarStatus'
const state = {
  sidebar: {
    opened: Cache.local().get(cacheKey, true),
    withoutAnimation: false,
    hide: false
  },
  device: 'desktop',
  size: Cache.local().get('vv__element_size', 'medium'),
  config: null
}

const mutations = {
  TOGGLE_SIDEBAR: state => {
    if (state.sidebar.hide) {
      return false
    }
    state.sidebar.opened = !state.sidebar.opened
    state.sidebar.withoutAnimation = false
    Cache.local().set(cacheKey, !!state.sidebar.opened)
  },
  CLOSE_SIDEBAR: (state, withoutAnimation) => {
    Cache.local().set(cacheKey, false)
    state.sidebar.opened = false
    state.sidebar.withoutAnimation = withoutAnimation
  },
  TOGGLE_DEVICE: (state, device) => {
    state.device = device
  },
  SET_SIZE: (state, size) => {
    state.size = size
    Cache.local().set('vv__element_size', size)
  },
  SET_SIDEBAR_HIDE: (state, status) => {
    state.sidebar.hide = status
  },
  SET_CONFIG: (state, config) => {
    state.config = config
  }
}

const actions = {
  toggleSideBar({ commit }) {
    commit('TOGGLE_SIDEBAR')
  },
  closeSideBar({ commit }, { withoutAnimation }) {
    commit('CLOSE_SIDEBAR', withoutAnimation)
  },
  toggleDevice({ commit }, device) {
    commit('TOGGLE_DEVICE', device)
  },
  setSize({ commit }, size) {
    commit('SET_SIZE', size)
  },
  toggleSideBarHide({ commit }, status) {
    commit('SET_SIDEBAR_HIDE', status)
  },
  // 获取系统配置
  initConfig({ commit }) {
    return new Promise((resolve, reject) => {
      getInitApi().then(data => {
          const config = data?.config || null
          if (!config) {
            reject('获取系统初始化信息失败')
          } else {
            commit('SET_CONFIG', config)
            resolve(config)
          }
        })
        .catch(error => {
          reject(error.msg || '获取系统初始化信息失败')
        })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
